package com.modules.upms.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.bean.config.YmlConfig;
import com.common.util.R;
import com.common.web.BaseController;
import com.modules.upms.entity.SysUser;
import com.modules.upms.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 */
@RestController
@RequestMapping(value = "/sys/user")
public class SysUserController extends BaseController {

    /**
     * 密码加密
     */
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    @Autowired
    private SysUserService sysUserService;

    /**
     * 属性文件读取
     */
    @Autowired
    private YmlConfig ymlConfig;


    /**
     * 获取当前登录用户信息
     *
     * @param authentication 信息
     * @return 用户信息
     */
    @GetMapping(value = "/current")
    public R<Object> current(Authentication authentication) {
        return R.success(authentication.getPrincipal());
    }


    /**
     * 通过手机号查询用户及其角色信息
     *
     * @param mobile 手机号
     * @return UseVo 对象
     */
    @GetMapping(value = "/findUserByMobile/{mobile}")
    public R<SysUser> findUserByMobile(@PathVariable String mobile) {
        return R.success(sysUserService.findUserByMobile(mobile));
    }

    /**
     * 通过OpenId查询
     *
     * @param openId openid
     * @return 对象
     */
    @GetMapping(value = "/findUserByOpenId/{openId}")
    public R<SysUser> findUserByOpenId(@PathVariable String openId) {
        return R.success(sysUserService.findUserByOpenId(openId));
    }

    /**
     * 分页查询用户
     *
     * @param sysUser 用户信息
     * @return 用户集合
     */
    @GetMapping(value = "/getUsersByRoleId")
    public R<List<SysUser>> getUsersByRoleId(@ModelAttribute SysUser sysUser) {
        return R.success(sysUserService.getUsersByRoleId(sysUser));
    }

    /**
     * 登录账号或手机号是否存在
     *
     * @param sysUser 用户信息
     * @return 用户集合
     */
    @GetMapping(value = "/isExists")
    public R<Boolean> isExists(@ModelAttribute SysUser sysUser) {
        return R.success(sysUserService.isExists(sysUser));
    }

    /**
     * 分页查询用户
     *
     * @param sysUser 用户信息
     * @return 用户集合
     */
    @GetMapping(value = "/listPage")
    public R<IPage> listPage(@ModelAttribute Page page, @ModelAttribute SysUser sysUser) {
        return R.success(sysUserService.getPage(page, sysUser));
    }

    /**
     * 重置密码
     *
     * @param dto
     * @return
     */
    @PostMapping(value = "/resetPassword")
    public R resetPassword(@RequestBody Dict dto) {
        String oldPassword = dto.getStr("oldPassword");
        String newPassword = dto.getStr("newPassword");
        String type = dto.getStr("type");
        String id = dto.getStr("id");
        if(StrUtil.isBlank(id)) {
            id = getUserId().toString();
        }

        SysUser user = sysUserService.getById(id);
        if (StrUtil.isNotBlank(type) && type.equals("INIT")) {
            //重置为初始密码 "123456"
            sysUserService.updateUserPasswordById(user.getId(),
                    ENCODER.encode(ymlConfig.getStr("initialPassword")),
                    null);
        }
        // 重置密码
        if ((StrUtil.isNotBlank(oldPassword) && StrUtil.isNotBlank(newPassword))) {
            if (!ENCODER.matches(oldPassword, user.getPassword())) {
                return R.error("旧密码错误");
            }
            sysUserService.updateUserPasswordById(user.getId(),
                    ENCODER.encode(newPassword),
                    new Date());
        }
        return R.success();
    }

    /**
     * 添加用户
     *
     * @param sysUser 用户信息
     * @return success/false
     */
    @PostMapping(value = "/save")
    public R<Boolean> save(@RequestBody SysUser sysUser) {
        if (sysUser.getIsNewRecord()) {
            sysUser.setPassword(ENCODER.encode(ymlConfig.getStr("initialPassword")));
        }
        sysUserService.saveOrUpdate(sysUser);
        return new R<>(Boolean.TRUE);
    }

    /**
     * 添加用户
     *
     * @param sysUser 用户信息
     * @return success/false
     */
    @PostMapping(value = "/updateStatus")
    public R<Boolean> updateStatus(@RequestBody SysUser sysUser) {
        sysUserService.updateStatus(sysUser);
        return new R<>(Boolean.TRUE);
    }


    /**
     * 上传用户头像
     * (多机部署有问题，建议使用独立的文件服务器)
     *
     * @param file 资源
     * @return filename map
     */
    @PostMapping(value = "/upload")
    public Map<String, String> upload(@RequestParam("file") MultipartFile file) {
//        String fileExt = FileUtil.extName(file.getOriginalFilename());
        Map<String, String> resultMap = new HashMap<>(1);
//        try {
//            StorePath storePath = fastFileStorageClient.uploadFile(file.getBytes(), fileExt);
//            resultMap.put("filename", fdfsPropertiesConfig.getFileHost() + storePath.getFullPath());
//        } catch (IOException e) {
//            logger.error("文件上传异常", e);
//            throw new RuntimeException(e);
//        }
        return resultMap;
    }

    /**
     * 删除用户信息
     *
     * @param id ID
     * @return R
     */
    @DeleteMapping(value = "/{id}")
    public R<Boolean> userDel(@PathVariable Integer id) {
        return new R<>(sysUserService.deleteById(id));
    }

}
